package gupao.concurrency.lock;

import gupao.concurrency.lock.utils.ThreadPoolService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ThreadPoolShutdown {
    public static void main(String[] args) throws InterruptedException {
//        testShutdown();
        testShutdownNow();
    }

    static void testShutdown() throws InterruptedException {
        String bizName = "shutdown-test";
        ThreadPoolExecutor threadPoolExecutor =
                ThreadPoolService.getOrCreateThreadPoolExecutor(bizName,
                        4,10,
                        new ArrayBlockingQueue<>(1000), true);
        submit100Tasks(threadPoolExecutor,bizName);
        ThreadPoolService.shutdown(bizName);
        threadPoolExecutor.awaitTermination(1,TimeUnit.MINUTES);
    }
    static void testShutdownNow() throws InterruptedException {
        String bizName = "shutdownNow-test";
        ThreadPoolExecutor threadPoolExecutor =
                ThreadPoolService.getOrCreateThreadPoolExecutor(bizName,
                        4,10,
                        new ArrayBlockingQueue<>(1000), true);
        submit100Tasks(threadPoolExecutor,bizName);
        List<Runnable> runnableList = ThreadPoolService.shutdownNow(bizName);
        runnableList.forEach(task -> log.info("not run task: {}", task));
    }

    static void submit100Tasks(ThreadPoolExecutor threadPoolExecutor, String bizName){
        int i = 0;
        for(; i < 100; i++){
            String taskName = "t" + (i+1);
            threadPoolExecutor.submit(new Runnable() {
                @Override
                public void run() {
                    log.info("task-{} is running", taskName);
                    try {
                        TimeUnit.MILLISECONDS.sleep(100);
                        log.info("task-{} finished.", taskName);
                    }catch (InterruptedException e){
                        log.warn("task-{} is interrupted.", taskName);
                    }
                }

                @Override
                public String toString() {
                    return "task-" + taskName;
                }
            });
        }
        log.info("submit {} tasks to thread pool {}", String.valueOf(i), bizName);
    }
}
